//
//  ZQOAuthViewController.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/15.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit

import SVProgressHUD
//路径
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")


class ZQOAuthViewController: UIViewController {

    
    var webView = UIWebView()
    
    override func loadView() {
      view = webView
        //代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

    
        
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        title = "微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName:"", target: self, action:#selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "直接登陆", imageName:"", target: self, action:#selector(fileaccount))
        
        //请求授权
        loadoathpage()
        
    }
    //  App Secret: 65a84cec0481a1bebcac9ee4b3f417a3
    //  App Key:    1943605865
    //  App
    @objc private func fileaccount () {
        let jsString = "document.getElementById('userId').value = '13863743521', document.getElementById('passwd').value = 'zhu415723'"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
    
    
    func loadoathpage() {
          let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + "http://www.baidu.com"
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        
        webView.loadRequest(req)
        
        
        
    }
    
    
    
    

    func close () {
        dismiss(animated: true, completion: nil)
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


//将模块化的功能 抽取出来~~

extension ZQOAuthViewController: UIWebViewDelegate{
    
    
    
    func webViewDidStartLoad(_ webView: UIWebView)
    {
        SVProgressHUD.show()
        
    }
    
    
    func webViewDidFinishLoad(_ webView: UIWebView)
    {
        SVProgressHUD.dismiss()
        
    }
    //   let url = request.url
    //   print("^    \(url)")
    //测试code
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //http://www.baidu.com/?code=bba95b61b97b50374438719a9f8bcd39
        let urlString = request.url?.absoluteString ?? ""
        let flag = "code="
        //是否包含 code
        if urlString.contains(flag){
            //能够截取code 能拿到 code后面的值
            let query = request.url?.query ?? ""
            
            let code = (query as NSString).substring(from: flag.characters.count)
//            print(code)
            let url = request.url
             print("^ -------   \(url)")
            print("^    \(code)")
            
            
            ZQUserAccountViewModel.shared.loadaccessToken(code: code, finished: { (isSecces : Bool) in
                if !isSecces {
                    //没有成功
                    SVProgressHUD.showError(withStatus: ErrorTip)
                    return
                }
                
                 print("请求成功")
                //发出通知
                
                NotificationCenter.default.post(name: NSNotification.Name(kRootViewController), object: "welcome")
               
//                UIApplication.shared.keyWindow?.rootViewController = ZQWelcomeController()
            })
                
            
            //获取了code之后就应该使用code 获取用户的token(访问接口的唯一标识)
            //如果获取了code之后就应该 return false 不加载页面
            //return false原因是不希望跳转成功后不再跳转别的页面
            
            return false
        }
        
        return true
        
    }
    
//    private func loadaccessToken(code:String){
//     //
//        let urlstring = "http://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id" : "1943605865",
//                          "client_secret" : client_secret,
//                          "grant_type" : "authorization_code",
//                          "code" : code,
//                          "redirect_uri" : "http://www.baidu.com"]
//        HMNetworkTools.shared.request(method: .POST, urlString: urlstring, parameters: parameters){ (responseObject, error) in
//            
//            if error != nil {
//                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
//                return
//            }
//            //请求成功
////            print(responseObject)
//        }
//    }
//        
//        private func loaduserInfo(dict : [String : Any]){
//            
//        let userString = "https://api.weibo.com/2/users/show.json"
//        let token = dict["access_token"]
//            
//        let uid = dict["uid"]
//            
//            let parameters =  ["access_token" : token,"uid" : uid]
//            
//            HMNetworkTools.shared.request(method: .GET, urlString: userString, parameters: parameters) { (responseObject, error ) in
//                if error != nil{
//                    
//                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是有网,但是手机坏啦!")
//                    return
//                    
//                }
//                
//                var userinfo = responseObject as! [String : Any]
//                
//                for (key,value) in dict{
//                    userinfo[key] = value
//                    
//                }
//  
//                //需要userinfo转成模型对象,
//                
//                //用归档的方式存储自定义模型
//                let userAccount = ZQUserAccount(dict: dict)
//               
//                self.saveUserAccount(userAccount: userAccount)
//                
//                
//                let cacheaccount = self.loadUserAccount()
////                print(cacheaccount)
//                
//              }
//            
//            }
//            
//            
//            private func saveUserAccount(userAccount : ZQUserAccount){
//           
//                
//                NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
//
//             }
//    
//    
//          private func loadUserAccount() -> ZQUserAccount? {
//                
//           let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
//                
//                if let userAccount = account as? ZQUserAccount {
//                    
//                    return userAccount
//                }
//                
//            return nil
//    }
    
  
    
}







